<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">

      <div class="title-container">
        <h3 class="title">ROBLOX开发者辅助平台</h3>
        <h3 class="title">（直接点登录）</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="Username"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="Password"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>

      <!-- <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">Login</el-button> -->
      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click="useqqlogin">登录</el-button>

      <div class="tips">
        <span style="margin-right:20px;cursor: pointer; " @click="useqqlogin">qq登录</span>
        <span style="margin-right:20px;cursor: pointer; " @click="useWxlogin">微信登录</span>
      </div>
      <div class="tips">
        <span style="margin-right:20px;">游客账户: admin</span>
        <span> 账户密码: 111111</span>
      </div>

    </el-form>

    <div class="btnText" style="color:#fff">
      <a href="https://beian.miit.gov.cn/">备案号：皖ICP备2022002176号</a>
    </div>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import { getToken, setToken } from '@/utils/auth'
// import QC from 'QC'

import axios from 'axios'

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: 'admin',
        password: '111111'
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created(){
    console.log('是不是测试 ',process.env.NODE_ENV === 'development')
    if (process.env.NODE_ENV === 'development') {

    }else{
      // 检查是否登录
      if (QC.Login.check()) {
        // 该处的openId，accessToken就是后台需要的参数了，后台可以通过这些参数获取临时登录凭证，然后就是自己的逻辑了
        QC.Login.getMe( (openId, accessToken) =>{
          if (openId !== undefined) {
          //openId 是用户的唯一标识，也是需要存到数据库的
            // console.log(openId)
            // console.log('-------------------------------')
            // console.log(accessToken)
            // 用JS SDK调用OpenAPI
            QC.api('get_user_info', {
              openId,accessToken,
              oauth_consumer_key:'078a0bdef3fd8e067b94554fdf676927'
            })
              // 指定接口访问成功的接收函数，s为成功返回Response对象
              .success( (s)=> {
                // 成功回调，通过s.data获取OpenAPI的返回数据
                this.denglu(openId,s.data)
                //我把调用成功的返回数据打印到控制台，可以把这些参数发请求到后台，存入数据库
                // this.$api.post('api/qqLogin', this.qqParam).then(res => {
                //   if (res.code === 'success') { }
                // })
              })
              // 指定接口访问失败的接收函数，f为失败返回Response对象
              .error(function (f) {
                // 失败回调
                alert('获取用户信息失败！')
              })
              //  this.$router.push({ path: '/home' })//登录成功我处理完后跳转到首页了
          }
        })
        console.log('已登录!')
        this.$message.info('qq成功登录')
      } else {
        console.log('未登录')
      }

    }
    
  },
  mounted(){
   
  },
  methods: {
    denglu(openId,info){
      console.log(' get_user_info ---------------------------------------------')
      let user_info = {
        openId,
        ...info
      }
      console.log(user_info)
      // 初始化 数据
      this.$Leancloud.dataRequest.getPage({
        page:1,
        pageSize:1,
        openId,
      },'users').then((res)=> {
        setToken(openId)
        if (res.list[0]) {
          this.$Leancloud.dataRequest.update(res.list[0].id,{
            openId,
            info:JSON.stringify(info)
          },'users',this).then(res=>{
            // console.log(res)
            this.$store.dispatch('user/getInfo',user_info).then(res=>{
              this.$router.push({ path: this.redirect || '/' })
            })
          })
        }else{
          this.$Leancloud.dataRequest.push({
            openId,
            info:JSON.stringify(info)
          },'users',this).then(res=>{
            // console.log(res)
            this.$store.dispatch('user/getInfo',user_info).then(res=>{
              this.$router.push({ path: this.redirect || '/' })
            })
          })
        }
      })
     
    },
    useWxlogin(){

    },
    useqqlogin(){
      
      // 直接登录
      if (process.env.NODE_ENV === 'development' || true) {
        let openId = "6A29DA8DB311B54DA7152B84DC297B22"
        let info = {
          city: "亳州",
          constellation: "",
          figureurl: "http://qzapp.qlogo.cn/qzapp/101993867/6A29DA8DB311B54DA7152B84DC297B22/30",
          figureurl_1: "http://qzapp.qlogo.cn/qzapp/101993867/6A29DA8DB311B54DA7152B84DC297B22/50",
          figureurl_2: "http://qzapp.qlogo.cn/qzapp/101993867/6A29DA8DB311B54DA7152B84DC297B22/100",
          figureurl_qq: "http://thirdqq.qlogo.cn/g?b=oidb&k=Ttib4P90gKOYjq8IrxUIlnw&s=640&t=1619510024",
          figureurl_qq_1: "http://thirdqq.qlogo.cn/g?b=oidb&k=Ttib4P90gKOYjq8IrxUIlnw&s=40&t=1619510024",
          figureurl_qq_2: "http://thirdqq.qlogo.cn/g?b=oidb&k=Ttib4P90gKOYjq8IrxUIlnw&s=100&t=1619510024",
          figureurl_type: "1",
          gender: "男",
          gender_type: 2,
          is_lost: 0,
          is_yellow_vip: "0",
          is_yellow_year_vip: "0",
          level: "0",
          msg: "",
          nickname: "如果____",
          openId: "6A29DA8DB311B54DA7152B84DC297B22",
          province: "安徽",
          ret: 0,
          vip: "0",
          year: "1999",
          yellow_vip_level: "0",
        }
        // this.denglu(openId,info)
        setToken(openId)
        this.$store.dispatch('user/getInfo',info).then(res=>{
          this.$router.push({ path: this.redirect || '/' })
        })
        return
      }

      // 直接弹出授权页面，授权过后跳转到回调页面进行登录处理
      QC.Login.showPopup({
        appId: '101993867',
        redirectURI: 'http://www.dreamvillage.work/#/login'
      })
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || '/' })
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  // src\assets\login.jpg
  background-image: url('~@/assets/login.jpg');
  background-size: cover;

  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;
.btnText{
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 20px;
}
.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 50px 35px 0;
    margin: 110px auto;
    overflow: hidden;

    background-position: center top;
    background-size: cover;
    z-index: 1;
  }
  .login-form:after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255,255,255,0.1);
    z-index: -1;

    background-image: url('~@/assets/login.jpg');
    background-position: center top;
    background-size: cover;
    background-attachment: fixed;
    -webkit-filter: blur(20px);
    -moz-filter: blur(20px);
    -ms-filter: blur(20px);
    -o-filter: blur(20px);
    filter: blur(20px);
    margin: -30px;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;
    // text-shadow: 0 0 10px rgb(65,158,255);
    // -webkit-text-stroke:3px rgb(65,158,255);
	  // -webkit-text-stroke: var(--stroke-width, 0.1em) var(--stroke-color, #c9721a);
    text-shadow: #000 3px 0 0, #000 0 1px 0, #000 -1px 0 0, #000 0 -1px 0;
    .title {
      font-size: 36px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
